#!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''
@Project ：henan_sumo
@File ：send.py
@IDE ：PyCharm
@Author ：xinyingjie
@Date ：2025/5/14 17:38
'''


import time
import re
from xml.etree import ElementTree as ET

XML_FILE = r"G:\xinyingjie\proj\henan_sumo\sumo\1.xml"

# 正则匹配一个完整的 <timestep> 块
TIMESTEP_PATTERN = re.compile(r'<timestep[^>]*>.*?</timestep>', re.DOTALL)


def parse_and_print_timesteps(content):
    matches = TIMESTEP_PATTERN.findall(content)
    for match in matches:
        try:
            root = ET.fromstring(match)
            time_attr = root.attrib.get('time', 'unknown')
            print(f"\n--- Timestep:{time.time()} {time_attr} ---")
            for vehicle in root.findall('vehicle'):
                vid = vehicle.get('id')
                x = vehicle.get('x')
                y = vehicle.get('y')
                speed = vehicle.get('speed')
                edge = vehicle.get('edge')
                # print(f"Vehicle ID: {vid}, Position: ({x}, {y}), Speed: {speed}, Edge: {edge}")
        except ET.ParseError as e:
            print(f"[ERROR] XML parse error: {e}")


def follow_file(file_path):
    with open(file_path, 'r', encoding='utf-8') as f:
        # 移动到文件末尾
        f.seek(0, 2)
        buffer = ""
        while True:
            line = f.readline()
            if not line:
                time.sleep(0.01)  # 等待新内容
                continue
            buffer += line
            # 如果缓冲区中有完整的 XML 片段再处理
            if '</timestep>' in buffer:
                full_xml = buffer
                buffer = ""
                parse_and_print_timesteps(full_xml)


if __name__ == "__main__":
    print("Starting to monitor XML file...")
    follow_file(XML_FILE)